package com.haiwei.poi.word.manager;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

@Slf4j
public final class FileUtil {

    public static File create(byte[] buffer, final String name, final String type) throws IOException {
        File file = File.createTempFile(name, type);

        IOUtils.write(buffer, new FileOutputStream(file));

        return file;
    }

    public static boolean delete(String fileName) {
        return delete(new File(fileName));
    }

    public static void delete(File ...files) {
        if (null == files || 0 == files.length) {
            return;
        }
        for (File file: files) {
            delete(file);
        }
    }

    public static boolean delete(File file) {
        if (null == file || !file.exists()) {
            return false;
        }
        return file.delete();
    }

    public static File toLocal(String fileurl) throws Exception {
        //new一个文件对象用来保存图片，默认保存当前工程根目录
        File file = new File(UUID.randomUUID() + "-temp.png");
        //创建输出流
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        try {
            URL url = new URL(fileurl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //设置请求方式为"GET"
            connection.setRequestMethod("GET");
            //超时响应时间为5秒
            connection.setConnectTimeout(5 * 1000);
            //通过输入流获取文件数据
            InputStream inStream = connection.getInputStream();
            //写入数据
            fileOutputStream.write(readInputStream(inStream));
            return file;
        } finally {
            //关闭输出流
            fileOutputStream.close();
        }
    }

    private static byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        try {
            //创建一个Buffer字符串
            byte[] buffer = new byte[1024];
            //每次读取的字符串长度，如果为-1，代表全部读取完毕
            int len = 0;
            //使用一个输入流从buffer里把数据读取出来
            while ((len = inStream.read(buffer)) != -1) {
                //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
                outStream.write(buffer, 0, len);
            }
            //关闭输入流
            inStream.close();
            //把outStream里的数据写入内存
            return outStream.toByteArray();
        } finally {
            outStream.close();
        }
    }

    public static void mkDir(String dirPath) {
        File file = new File(dirPath);
        if (file.exists() && !file.delete()) {
            log.warn("dirPath [{}] exists and fail to delete...", dirPath);
        }
        boolean result = file.mkdir();
        if(!result){
            log.warn("dirPath [{}] exists and fail to create...", dirPath);
        }
    }

    public static File toLocal(String fileUrl, String name) throws Exception {
        File file = new File(name);
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        try {
            URL url = new URL(fileUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5 * 1000);
            InputStream inStream = connection.getInputStream();
            fileOutputStream.write(readInputStream(inStream));
        } catch (Exception e) {
            log.warn("[export images] download image fail : {} , error: {}", fileUrl, e);
        } finally {
            fileOutputStream.close();
        }
        return file;
    }

    public static boolean delFile( File file) {
        if (!file.exists()) {
            return false;
        }
        if (file.isFile()) {
            return file.delete();
        } else {
            File[] files = file.listFiles();
            if(files == null || files.length==0){
                return false;
            }
            for (File f : files) {
                delFile(f);
            }
            return file.delete();
        }
    }
}
